import React, { useState, useEffect, useMemo } from 'react';
import { Modal, Form, Input, App, Space, Popconfirm, Tag, Tooltip, Select } from 'antd';
import { Button } from 'eaid';
import { EditOutlined, DeleteOutlined, EyeOutlined, SyncOutlined, CloseOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import Modals from '@/components/modals/Modals';
import Tables from '@/components/tables/tables';
import nl2sqlService from '@/api/services/nl2sqlService';
import { ConnectionInfo, SearchTableColumnsResponse, TableColumn, TableRelation, UpdateTableRequest } from '@/types/nl2sql/type';
import BasicInfoEditModal from './basic-info-edit-modal';
import TablePreviewModal from './table-preview-modal';
import UpdateTableModal from './update-table-modal';
import ColumnEditModal from './column-edit-modal';

interface TableManagementModalProps {
  visible: boolean;
  onCancel: () => void;
  tableInfo: {
    table_data_id: string;
    table_name: string;
  } | null;
  connectionInfo: ConnectionInfo | null;
  onRefresh: () => void;
}

const TableManagementModal: React.FC<TableManagementModalProps> = ({
  visible,
  onCancel,
  tableInfo,
  connectionInfo,
  onRefresh,
}) => {
  const { message } = App.useApp();
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState<SearchTableColumnsResponse | null>(null);
  const [searchValue, setSearchValue] = useState('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [isEditingBasicInfo, setIsEditingBasicInfo] = useState(false);
  const [previewModalVisible, setPreviewModalVisible] = useState(false);
  const [updateModalVisible, setUpdateModalVisible] = useState(false);
  const [columnEditModalVisible, setColumnEditModalVisible] = useState(false);
  const [editingColumnData, setEditingColumnData] = useState<TableColumn | null>(null);
  const [editingRowKey, setEditingRowKey] = useState<string | null>(null);
  const [editingField, setEditingField] = useState<string | null>(null);
  const [editingValue, setEditingValue] = useState<string>('');

  // 数据库支持的数据类型
  const dataTypes = [
    'INTEGER', 'BIGINT', 'SMALLINT', 'TINYINT',
    'VARCHAR', 'CHAR', 'TEXT', 'LONGTEXT',
    'DECIMAL', 'NUMERIC', 'FLOAT', 'DOUBLE',
    'DATE', 'DATETIME', 'TIMESTAMP', 'TIME',
    'BOOLEAN', 'BIT', 'BLOB', 'LONGBLOB',
    'JSON', 'XML', 'UUID'
  ];

  // 使用 useRequest 调用 updateTable 接口保存列信息
  const { runAsync: updateTableColumns, loading: updateColumnsLoading } = useRequest(
    async (requestData: UpdateTableRequest) => {
      if (!connectionInfo?.schema_dataset || !tableInfo?.table_data_id) {
        throw new Error('缺少必要的连接信息或表信息');
      }

      const response = await nl2sqlService.updateTable(
        connectionInfo.schema_dataset, // datasetId
        tableInfo.table_data_id,       // tableId
        requestData
      );

      return response;
    },
    {
      manual: true,
      onSuccess: (response) => {
        console.log('列信息保存成功:', response);
      },
      onError: (error) => {
        console.error('保存列信息失败:', error);
      },
    }
  );

  // 获取表列数据
  const fetchTableColumns = async () => {
    if (!tableInfo?.table_data_id) return;

    setLoading(true);
    try {
      const response = await nl2sqlService.searchTableColumns(tableInfo.table_data_id, {
        isPage: false,
        offset: -1,
        page: pagination.current,
        page_size: pagination.pageSize,
      });
      setTableData(response);
      console.log('response', response);
      setPagination(prev => ({
        ...prev,
        total: response.total,
      }));
    } catch (error) {
      console.error('获取表列信息失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 监听弹窗显示状态和分页变化
  useEffect(() => {
    if (visible && tableInfo) {
      fetchTableColumns();
      setColumnEditModalVisible(false);
      setEditingColumnData(null);
      setEditingRowKey(null);
      setEditingField(null);
      setEditingValue('');
    }
  }, [visible, tableInfo, pagination.current, pagination.pageSize, searchValue]);

  useEffect(() => {
    setPagination({
      current: 1,
      pageSize: 10,
      total: 0,
    });
    setSearchValue(''); // 重置搜索值
  }, [visible]);

  // 处理分页变化
  const handlePaginationChange = (page: number, pageSize: number) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize,
    }));
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchValue(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 处理编辑列
  const handleEditColumn = (column: TableColumn) => {
    setEditingColumnData(column);
    setColumnEditModalVisible(true);
  };

  // 处理列编辑确认
  const handleColumnEditOk = async (values: any) => {
    try {
      if (!editingColumnData || !tableData?.table_info?.table_columns) return;

      // 更新本地数据
      const updatedColumns = tableData.table_info.table_columns.map(col =>
        col.column_name === editingColumnData.column_name
          ? { ...col, ...values }
          : col
      );

      // 构建更新请求参数
      const updateRequest: UpdateTableRequest = {
        table_name: tableInfo?.table_name || '',
        table_description: tableData.table_info.table_description || '',
        table_primary_key: tableData.table_info.table_primary_key || '',
        table_relations: tableData.table_info.table_relations || [],
        table_columns: updatedColumns,
      };

      // 调用 updateTable 接口保存数据
      await updateTableColumns(updateRequest);

      // 更新本地状态
      setTableData({
        ...tableData,
        table_info: {
          ...tableData.table_info,
          table_columns: updatedColumns,
        },
      });

      // 关闭弹窗
      setColumnEditModalVisible(false);
      setEditingColumnData(null);

    } catch (error) {
      console.error('保存列信息失败:', error);
    }
  };

  // 处理列编辑取消
  const handleColumnEditCancel = () => {
    setColumnEditModalVisible(false);
    setEditingColumnData(null);
  };

  // 处理单元格编辑开始
  const handleCellEdit = (record: TableColumn, field: string) => {
    setEditingRowKey(record.column_name);
    setEditingField(field);
    setEditingValue(record[field as keyof TableColumn] as string || '');
  };

  // 处理键盘事件
  const handleKeyDown = (e: React.KeyboardEvent, record: TableColumn) => {
    if (e.key === 'Enter') {
      handleCellSave(record);
    } else if (e.key === 'Escape') {
      handleCellCancel();
    }
  };

  // 处理单元格编辑保存
  const handleCellSave = async (record: TableColumn) => {
    try {
      if (!editingField || !tableData?.table_info?.table_columns) return;

      // 更新本地数据
      const updatedColumns = tableData.table_info.table_columns.map(col =>
        col.column_name === record.column_name
          ? { ...col, [editingField]: editingValue }
          : col
      );

      // 构建更新请求参数
      const updateRequest: UpdateTableRequest = {
        table_name: tableInfo?.table_name || '',
        table_description: tableData.table_info.table_description || '',
        table_primary_key: tableData.table_info.table_primary_key || '',
        table_relations: tableData.table_info.table_relations || [],
        table_columns: updatedColumns,
      };

      // 调用 updateTable 接口保存数据
      await updateTableColumns(updateRequest);

      // 更新本地状态
      setTableData({
        ...tableData,
        table_info: {
          ...tableData.table_info,
          table_columns: updatedColumns,
        },
      });

      // 退出编辑模式
      setEditingRowKey(null);
      setEditingField(null);
      setEditingValue('');

      message.success('保存成功');
    } catch (error) {
      console.error('保存失败:', error);
    }
  };

  // 处理单元格编辑取消
  const handleCellCancel = () => {
    setEditingRowKey(null);
    setEditingField(null);
    setEditingValue('');
  };







  // 处理删除列
  const handleDeleteColumn = async (column: TableColumn) => {
    try {
      if (!connectionInfo?.schema_dataset || !tableInfo?.table_data_id) {
        message.error('缺少必要的连接信息或表信息');
        return;
      }

      // 调用 deleteColumn 接口删除列
      await nl2sqlService.deleteColumn(
        connectionInfo.schema_dataset, // datasetId
        tableInfo.table_data_id,       // tableId
        column.column_name             // columnName
      );

      // 重新获取表列数据
      await fetchTableColumns();
      onRefresh();
      message.success('列删除成功');
    } catch (error) {
      console.error('删除列失败:', error);
    }
  };

  // 处理预览数据表
  const handlePreviewTable = () => {
    setPreviewModalVisible(true);
  };

  // 处理更新数据表
  const handleUpdateTable = () => {
    setUpdateModalVisible(true);
  };

  // 处理编辑基础信息
  const handleEditBasicInfo = () => {
    setIsEditingBasicInfo(true);
  };

  // 处理保存基础信息
  const handleSaveBasicInfo = async (values: any) => {
    try {
      // 基础信息已经在 basic-info-edit-modal 中通过 updateTable 接口保存
      // 这里只需要处理成功后的逻辑
      console.log('基础信息保存成功:', values);
      // message.success('基础信息保存成功');
      setIsEditingBasicInfo(false);
      // 刷新表数据以显示最新的基础信息
      await fetchTableColumns();
    } catch (error) {
      console.error('保存基础信息失败:', error);
    }
  };

  // 处理取消编辑
  const handleCancelEdit = () => {
    setIsEditingBasicInfo(false);
  };

  // 获取编辑弹窗的初始数据
  const getEditModalInitialData = () => {
    if (!tableData?.table_info) return null;

    return {
      table_description: tableData.table_info.table_description || '',
      table_primary_key: tableData.table_info.table_primary_key || '',
      table_relations: tableData.table_info.table_relations || [],
    };
  };

  // 处理预览弹窗关闭
  const handlePreviewModalClose = () => {
    setPreviewModalVisible(false);
  };

  // 处理更新弹窗关闭
  const handleUpdateModalClose = () => {
    setUpdateModalVisible(false);
  };

  // 处理更新弹窗确认
  const handleUpdateModalOk = async () => {
    try {
      // 关闭更新弹窗
      setUpdateModalVisible(false);

      // 刷新表数据
      await fetchTableColumns();
      onRefresh();

      message.success('数据表更新成功');
    } catch (error) {
      message.error('数据表更新失败');
      console.error('更新数据表失败:', error);
    }
  };

  // // isPage: true 过滤列数据
  // const filteredColumns = tableData?.table_info?.table_columns?.filter((column) => {
  //   if (!searchValue) return true;
  //   return (
  //     column.column_name.toLowerCase().includes(searchValue.toLowerCase()) ||
  //     column.column_description.toLowerCase().includes(searchValue.toLowerCase()) ||
  //     column.column_zh_name.toLowerCase().includes(searchValue.toLowerCase())
  //   );
  // }) || [];

  // 过滤列数据 - 使用 useMemo 优化性能
  const filteredColumns = useMemo(() => {
    return tableData?.table_info?.table_columns?.filter((column) => {
      if (!searchValue) return true;
      return (
        column.column_name.toLowerCase().includes(searchValue.toLowerCase()) ||
        column.column_description.toLowerCase().includes(searchValue.toLowerCase()) ||
        column.column_zh_name.toLowerCase().includes(searchValue.toLowerCase())
      );
    }) || [];
  }, [tableData?.table_info?.table_columns, searchValue]);

  // 分页后的数据 - 使用 useMemo 优化性能
  const paginatedColumns = useMemo(() => {
    const data = filteredColumns.slice(
      (pagination.current - 1) * pagination.pageSize,
      pagination.current * pagination.pageSize
    );
    if (data.length === 0 && pagination.current > 1) {
      setPagination(prev => ({
        ...prev,
        current: prev.current - 1,
      }));
    }
    return data;
  }, [filteredColumns, pagination.current, pagination.pageSize]);

  // 表格列定义
  const columns = [
    {
      title: '列名',
      dataIndex: 'column_name',
      key: 'column_name',
      width: 80,
      render: (text: string) => (
        <span className="font-medium text-gray-900">{text}</span>
      ),
    },
    {
      title: '列中文名称',
      dataIndex: 'column_zh_name',
      key: 'column_zh_name',
      width: 80,
      render: (text: string, record: TableColumn) => {
        const isEditing = editingRowKey === record.column_name && editingField === 'column_zh_name';

        if (isEditing) {
          return (
            <div className="flex items-center space-x-2">
              <Input
                value={editingValue}
                onChange={(e) => setEditingValue(e.target.value)}
                onKeyDown={(e) => handleKeyDown(e, record)}
                size="small"
                autoFocus
              />
              {/* <Button
                type="text"
                size="small"
                icon={<EditOutlined />}
                onClick={() => handleCellSave(record)}
                className="text-green-600 hover:text-green-800"
              >
                保存
              </Button>
              <Button
                type="text"
                size="small"
                icon={<CloseOutlined />}
                onClick={handleCellCancel}
                className="text-red-600 hover:text-red-800"
              >
                取消
              </Button> */}
            </div>
          );
        }

        return (
          <div className="group relative">
            <span className="text-gray-900">{text || '-'}</span>
            <EditOutlined
              className="ml-2 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer hover:text-blue-600"
              onClick={() => handleCellEdit(record, 'column_zh_name')}
              title="点击编辑"
            />
          </div>
        );
      },
    },
    {
      title: '列描述',
      dataIndex: 'column_description',
      key: 'column_description',
      width: 100,
      render: (text: string, record: TableColumn) => {
        const isEditing = editingRowKey === record.column_name && editingField === 'column_description';

        if (isEditing) {
          return (
            <div className="flex items-center space-x-2">
              <Input
                value={editingValue}
                onChange={(e) => setEditingValue(e.target.value)}
                onKeyDown={(e) => handleKeyDown(e, record)}
                size="small"
                autoFocus
              />
              {/* <Button
                type="text"
                size="small"
                icon={<EditOutlined />}
                onClick={() => handleCellSave(record)}
                className="text-green-600 hover:text-green-800"
              >
                保存
              </Button>
              <Button
                type="text"
                size="small"
                icon={<CloseOutlined />}
                onClick={handleCellCancel}
                className="text-red-600 hover:text-red-800"
              >
                取消
              </Button> */}
            </div>
          );
        }

        return (
          <div className="group relative">
            <span className="text-gray-900">{text || '-'}</span>
            <EditOutlined
              className="ml-2 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer hover:text-blue-600"
              onClick={() => handleCellEdit(record, 'column_description')}
              title="点击编辑"
            />
          </div>
        );
      },
    },
    {
      title: '数据类型',
      dataIndex: 'data_type',
      key: 'data_type',
      width: 50,
      render: (text: string, record: TableColumn) => (
        <Tag color="blue">{text}</Tag>
      ),
    },
    {
      title: '是否枚举',
      dataIndex: 'is_enum',
      key: 'is_enum',
      width: 50,
      render: (isEnum: boolean, record: TableColumn) => (
        <Tag color={isEnum ? 'green' : 'default'}>
          {isEnum ? '是' : '否'}
        </Tag>
      ),
    },
    {
      title: '枚举类型候选值',
      dataIndex: 'enum_values',
      key: 'enum_values',
      width: 100,
      render: (values: string[], record: TableColumn) => (
        values && values.length > 0 ? (
          <div className="max-w-[140px] text-sm text-gray-900">
            {values.join(', ')}
          </div>
        ) : ''
      ),
    },
    {
      title: '数据样例',
      dataIndex: 'examples',
      key: 'examples',
      width: 100,
      render: (examples: string[], record: TableColumn) => (
        examples && examples.length > 0 ? (
          <div className="max-w-[140px] text-sm text-gray-900">
            {examples.join(', ')}
          </div>
        ) : ''
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      // fixed: 'right' as const,
      render: (_: any, record: TableColumn) => {
        const isEditing = editingRowKey === record.column_name;

        if (isEditing) {
          return (
            <Space size="small">
              <Button
                type="text"
                size="small"
                icon={<EditOutlined />}
                onClick={() => handleCellSave(record)}
                className="text-green-600 hover:text-green-800"
              >
                保存
              </Button>
              <Button
                type="text"
                size="small"
                icon={<CloseOutlined />}
                onClick={handleCellCancel}
                className="text-red-600 hover:text-red-800"
              >
                取消
              </Button>
            </Space>
          );
        }

        return (
          <Space size="small">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEditColumn(record)}
              className="text-blue-600 hover:text-blue-800"
            >
              编辑
            </Button>
            <Popconfirm
              title="删除后可能会影响对该列数据的理解,是否确认删除?"
              onConfirm={() => handleDeleteColumn(record)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="text"
                size="small"
                icon={<DeleteOutlined />}
                // onClick={() => handleDeleteColumn(record)}
                className="text-red-800"
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  // 渲染省略文本组件
  const renderTruncatedText = (text: string, maxLength: number = 20) => {
    if (!text || text.length <= maxLength) {
      return <span className="font-normal text-[var(--text-3)]">{text || '-'}</span>;
    }

    return (
      <Tooltip title={text} placement="top">
        <span className="font-normal text-[var(--text-3)]">
          <span style={{ whiteSpace: 'nowrap' }}>{text.substring(0, maxLength) + '...'}</span>
        </span>
      </Tooltip>
    );
  };

  return (
    <>
      <Modals
        title={`数据表：${tableInfo?.table_name || ''}`}
        open={visible}
        onCancel={onCancel}
        width={1200}
        footer={null}
        destroyOnHidden={true}
        maskClosable={false}
        modelContentClassName="!p-0 mx-3 !max-h-[calc(100vh-50px)] overflow-y-auto"
      >
        <div className="space-y-6">
          {/* 基础信息 */}
          <div className="bg-gray-50 rounded-lg px-4 pt-4">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center font-semibold text-[var(--text-5)]">
                基础信息
                <EditOutlined className="ml-2 text-gray-400" onClick={handleEditBasicInfo} />
              </div>
            </div>

            {/* 基础信息展示 */}
            <div className="grid grid-cols-3 gap-4 text-sm">
              <div className="flex items-center">
                <span className="text-[var(--text-3)] min-w-[80px] whitespace-nowrap">数据表描述:</span>
                <div className="text-[var(--text-3)] flex-1 overflow-hidden whitespace-nowrap text-ellipsis pr-2" style={{ minWidth: 0 }}>
                  {renderTruncatedText(tableData?.table_info?.table_description || '', 25)}
                </div>
              </div>
              <div className="flex items-center">
                <span className="text-[var(--text-3)] min-w-[80px] whitespace-nowrap">数据表主键:</span>
                <div className="text-[var(--text-3)] flex-1 overflow-hidden whitespace-nowrap text-ellipsis pr-2" style={{ minWidth: 0 }}>
                  {renderTruncatedText(tableData?.table_info?.table_primary_key || '', 25)}
                </div>
              </div>
              <div className="flex items-center">
                <span className="text-[var(--text-3)] min-w-[50px] whitespace-nowrap">表关系:</span>
                <div className="text-[var(--text-3)] flex-1 overflow-hidden whitespace-nowrap text-ellipsis pr-2" style={{ minWidth: 0 }}>
                  {renderTruncatedText(
                    tableData?.table_info?.table_relations
                      ? tableData.table_info.table_relations.map(rel =>
                        `${rel.from_table_name}.${rel.from_column_name},${rel.relation_type || '-'},${rel.to_table_name}.${rel.to_column_name}`
                      ).join('; ')
                      : '',
                    50
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* 数据表字段信息 */}
          <div className="bg-white rounded-lg">
            <div className="px-4 bg-gray-50">
              <div className="flex items-center justify-between">
                <h3 className="flex items-center font-semibold text-[var(--text-5)]">数据表字段信息</h3>
                <div className="flex items-center space-x-3">
                  <div className="w-64">
                    <Input.Search
                      placeholder="搜索"
                      allowClear
                      onSearch={handleSearch}
                      onChange={(e) => setSearchValue(e.target.value)}
                    />
                  </div>
                  <Button
                    type="secondary"
                    icon={<EyeOutlined />}
                    onClick={handlePreviewTable}
                  >
                    预览数据表
                  </Button>
                  <Button
                    type="secondary"
                    icon={<SyncOutlined />}
                    onClick={handleUpdateTable}
                  >
                    更新数据表
                  </Button>
                </div>
              </div>
            </div>

            <div className="p-4">
              <Tables
                columns={columns}
                dataSource={paginatedColumns}
                rowKey="column_name"
                loading={loading}
                size="middle"
                paginationProps={{
                  current: pagination.current,
                  pageSize: pagination.pageSize,
                  total: tableData?.total || 0,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total) => `共 ${total} 项数据`,
                  onChange: handlePaginationChange,
                }}
              />
            </div>
          </div>
        </div>
      </Modals>

      {/* 基础信息编辑弹窗 */}
      <Modals
        title="基础信息编辑"
        open={isEditingBasicInfo}
        onCancel={handleCancelEdit}
        width={800}
        footer={null}
        destroyOnHidden={true}
        maskClosable={false}
        modelContentClassName="!p-0 mx-3"
      >
        <BasicInfoEditModal
          visible={isEditingBasicInfo}
          onCancel={handleCancelEdit}
          onOk={handleSaveBasicInfo}
          initialData={getEditModalInitialData()}
          tableName={tableInfo?.table_name || ''}
          connectionInfo={connectionInfo}
        />
      </Modals>

      {/* 数据表预览弹窗 */}
      <TablePreviewModal
        visible={previewModalVisible}
        onCancel={handlePreviewModalClose}
        tableInfo={tableInfo}
        connectionInfo={connectionInfo}
      />

      {/* 数据表更新弹窗 */}
      <UpdateTableModal
        visible={updateModalVisible}
        onCancel={handleUpdateModalClose}
        onOk={handleUpdateModalOk}
        tableName={tableInfo?.table_name || ''}
        tableId={tableInfo?.table_data_id || ''}
        databaseId={connectionInfo?.database_id || ''}
      />

      {/* 列编辑弹窗 */}
      <ColumnEditModal
        visible={columnEditModalVisible}
        onCancel={handleColumnEditCancel}
        onOk={handleColumnEditOk}
        column={editingColumnData}
        tableId={tableInfo?.table_data_id || ''}
        databaseId={connectionInfo?.database_id || ''}
      />
    </>
  );
};

export default TableManagementModal; 